package com.spring.mybatis.core;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 使用 FactoryBean 来创建 Mapper 代理对象
 * @author yangjian
 */
public class MybatisMapperFactoryBean implements FactoryBean {

	private Class mapperInterface;

	private SqlSession sqlSession;

	public MybatisMapperFactoryBean(Class mapperInterface) {
		this.mapperInterface = mapperInterface;
	}

	@Autowired
	public void setSqlSession(SqlSessionFactory sqlSessionFactory)
	{
		this.sqlSession = sqlSessionFactory.openSession();
	}

	@Override
	public Object getObject()
	{
		// 添加 mapper 到 MapperRegistry
		sqlSession.getConfiguration().addMapper(mapperInterface);
		// 生成 mybatis mapper 代理对象
		return sqlSession.getMapper(mapperInterface);
	}

	@Override
	public Class<?> getObjectType()
	{
		return mapperInterface;
	}
}
